//
//  UIViewControllerExtension.swift
//  DemoNavBar
//
//  Created by YangHuan on 2019/12/13.
//  Copyright © 2019 YangHuan. All rights reserved.
//

import Foundation
import AEAlertView

extension UIViewController {
    func setClearNavigation() {
        navigationController?.navigationBar.isTranslucent = true
        navigationController?.navigationBar.setBackgroundImage(
            UIImage(), for: UIBarMetrics.default)
        navigationController?.navigationBar.shadowImage = UIImage()
    }
    
    func setNormalNavigation() {
        navigationController?.navigationBar.setBackgroundImage(
            UIImage(named: "barImg"), for: .default)
        navigationController?.navigationBar.isTranslucent = false
    }
    
    func setImageWithColorNavigation(image: UIImage) {
        navigationController?.navigationBar.setBackgroundImage(
            image, for: .default)
        navigationController?.navigationBar.isTranslucent = false
    }
   
    func defaultLeftBackIetm(title: String, image:String) {
           self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: image), style: .plain, target: self, action: #selector(navigationBack))
        }
    
      /// 返回上一控制器
      @objc private func navigationBack() {
        navigationController?.popViewController(animated: true)
         
      }
}

// MARK: - 自定义导航栏
public extension UIViewController {
    /// 注意循环引用
    func setupCustomClearNaviBar(title: String, shouldBack: Bool, rightItem: String?, leftAction: (() -> ())? = nil, rightAction:(() -> ())?) {
        self.setupCustomNaviBar(title: title, image: nil, isTranslucent: true, shouldBack: shouldBack, rightItem: rightItem, rightImage: nil, leftAction: leftAction, rightAction: rightAction)
    }
    func setupCustomClearNaviBar(title: String, shouldBack: Bool, rightImage: UIImage?, leftAction: (() -> ())? = nil, rightAction:(() -> ())?) {
        self.setupCustomNaviBar(title: title, image: nil, isTranslucent: true, shouldBack: shouldBack, rightItem: nil, rightImage: rightImage, leftAction: leftAction, rightAction: rightAction)
    }
    
    func setupCustomNormalNaviBar(title: String, shouldBack: Bool, rightItem: String?, leftAction: (() -> ())? = nil,  rightAction:(() -> ())?) {
        self.setupCustomNaviBar(title: title, image: UIImage(named: "barImg"), isTranslucent: true, shouldBack: shouldBack, rightItem: rightItem, rightImage: nil, leftAction: leftAction, rightAction: rightAction)
    }
    
    
    func setupCustomNaviBar(title: String, image: UIImage?, isTranslucent: Bool, shouldBack: Bool, rightItem: String?, rightImage: UIImage?, leftAction: (() -> ())?, rightAction:(() -> ())?) {
        let backView = UIImageView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: naviAddStatusHeight))
        backView.isUserInteractionEnabled = true
        let customBar = UINavigationBar(frame: CGRect(x: 0, y: statusBarHeight, width: kScreenWidth, height: naviBarHeight))
        customBar.isTranslucent = isTranslucent
        backView.image = image
        if image == nil {
            backView.backgroundColor = UIColor.clear
            customBar.setBackgroundImage(
                UIImage(), for: UIBarMetrics.default)
            customBar.shadowImage = UIImage()
        } else {
            backView.image = image
            customBar.setBackgroundImage(
                UIImage(), for: UIBarMetrics.default)
        }
        backView.addSubview(customBar)
        
        view.addSubview(backView)
        /// title
        let naviItem = UINavigationItem(title: title)
        customBar.items = [naviItem]
        customBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font: kFont18]
        customBar.tintColor = UIColor.white
        if rightItem != nil {
            /// right
            let rightItem = UIBarButtonItem(title: rightItem!, style: UIBarButtonItem.Style.done , handler: {
                rightAction?()
            })
            naviItem.rightBarButtonItem = rightItem
        }
        
        if rightImage != nil {
            let ri = UIBarButtonItem(image: rightImage, style: UIBarButtonItem.Style.plain) {
                rightAction?()
            }
            naviItem.rightBarButtonItem = ri
        }
        if shouldBack {
            let leftItem = UIBarButtonItem(image: UIImage(named: "back"), style: .plain) { [weak self] in
                if leftAction != nil {
                    leftAction!()
                    return
                }
                if self?.presentingViewController != nil {
                    self?.dismiss(animated: true, completion: nil)
                } else {
                    self?.navigationController?.popViewController(animated: true)
                }
            }
            naviItem.leftBarButtonItem = leftItem
        }
    }
}

public extension UIViewController {
    
    typealias AlertAction = (_ index: Int) -> Void
   func alert(style: UIAlertController.Style = .alert,title: String?, message: String?, buttons: [String], tapped: @escaping AlertAction) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: style)
        var actions = buttons.enumerated().map { (index, item) in
            return UIAlertAction(title: item, style: .default, handler: { _ in
                tapped(index)
            })
        }
        if style == .actionSheet {
            actions.append(UIAlertAction(title: Localized(key: "Cancle"), style: .cancel, handler: nil))
        }
        actions.forEach { $0.setValue(UIColor("#363333"), forKey: "titleTextColor") }
        actions.forEach { alert.addAction($0) }
        present(alert, animated: true, completion: nil)
    }
    
  func elAlert(style: UIAlertController.Style = .alert,title: String?, message: String?, buttons: [String], tapped: @escaping AlertAction) {
    let alert = ALAlertView(style: .defaulted, title: title ?? "", message: message ?? "")
        alert.contentViewTopMargin = 5
        alert.titleTopMargin = 15
        alert.messageHeight = 50
        alert.buttonColor = UIColor(red: 253/255.0, green: 101/255.0, blue: 141/255.0, alpha: 1.0)
        alert.cancelButtonColor = UIColor(red: 178/255.0 , green: 171/255.0, blue: 226/255.0, alpha: 1.0)
        
        
        let actions = buttons.enumerated().map { (arg) -> AEAlertAction? in
            let (index, item) = arg
            if index == 0 {
                return AEAlertAction(title: item, style: .cancel, handler: { (_) in
                    tapped(index)
                    alert.dismiss()
                })
            }
            return AEAlertAction(title: item, style: .defaulted, handler: { (_) in
                tapped(index)
                alert.dismiss()
            })
        }
        actions.forEach { alert.addAction(action: ($0)!) }
        
        alert.show()
    }
   
}


extension UIViewController{
    
    /// Returns the current application's top most view controller.
    open class var topMost: UIViewController? {
        let topMost = self.topMost(of: appDelegate.window?.rootViewController)
        return topMost
    }
    
    
    /// Returns the top most view controller from given view controller's stack.
    open class func topMost(of viewController: UIViewController?) -> UIViewController? {
        // presented view controller
        if let presentedViewController = viewController?.presentedViewController {
            return self.topMost(of: presentedViewController)
        }
        
        // UITabBarController
        if let tabBarController = viewController as? UITabBarController,
            let selectedViewController = tabBarController.selectedViewController {
            return self.topMost(of: selectedViewController)
        }
        
        // UINavigationController
        if let navigationController = viewController as? UINavigationController,
            let visibleViewController = navigationController.visibleViewController {
            return self.topMost(of: visibleViewController)
        }
        
        // UIPageController
        if let pageViewController = viewController as? UIPageViewController,
            pageViewController.viewControllers?.count == 1 {
            return self.topMost(of: pageViewController.viewControllers?.first)
        }
        
        // child view controller
        for subview in viewController?.view?.subviews ?? [] {
            if let childViewController = subview.next as? UIViewController {
                return self.topMost(of: childViewController)
            }
        }
        
        return viewController
    }
    
}

